package ru.example.telepuzik.gif;

import android.accounts.AccountManager;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.Api;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.vk.sdk.VKAccessToken;
import com.vk.sdk.VKScope;
import com.vk.sdk.VKSdk;
import com.vk.sdk.VKSdkListener;
import com.vk.sdk.VKUIHelper;
import com.vk.sdk.api.VKApi;
import com.vk.sdk.api.VKApiConst;
import com.vk.sdk.api.VKError;
import com.vk.sdk.api.VKParameters;
import com.vk.sdk.api.VKRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends FragmentActivity
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

    private final static String G_PLUS_SCOPE ="oauth2:https://www.googleapis.com/auth/plus.me";//права доступа
    private final static String USER_INFO_SCOPE ="https://www.googleapis.com/auth/userinfo.profile";//получение имя фамилии фото и тд
    private final static String EMAIL_SCOPE ="https://www.googleapis.com/auth/userinfo.email";//получение email
    private final static String SCOPES = G_PLUS_SCOPE + " " + USER_INFO_SCOPE + " " + EMAIL_SCOPE;
    String tokenGoogle;//токен гугла
    private static final String API_URL = "https://docs.google.com/feeds/default/private/full";

    private GoogleApiClient googleApiClient;
    private boolean signInIsClicked;
    private boolean intentInProgress;
    private ConnectionResult mConnectionResult;
    private static final int RC_SIGN_IN = 0;

    private static final String TAG = "ALARMANA";

    private static final String VK_APP_ID = "4818942";
    private VKRequest currentRequest;

    private Button loginButton;
    private Button btnPost;
    String personImageURL;
    VKAccessToken tokenVk;
    Map<String, String> parameters = new HashMap<String, String>();

    private String VK_API_URL = "https://api.vkontakte.ru/method/";
    private String VK_POST_TO_WALL_URL = VK_API_URL + "wall.post?";
    Api api;
    @Override//1
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        SignInButton signInButton = (SignInButton) findViewById(R.id.signInButton);
        signInButton.setOnClickListener(this);

        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();

        //setListAdapter(listAdapter);
        //где-то тут вывод всех документов на экран
        VKSdk.initialize(sdkListener, VK_APP_ID);
        VKUIHelper.onCreate(this);


        loginButton = (Button) findViewById(R.id.login_button);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("VkDemoApp", "authorize ");
                VKSdk.authorize(VKScope.WALL);
            }
        });

        btnPost = (Button) findViewById(R.id.btnPost);
        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //postToWall();

            }
        });

        if (VKSdk.wakeUpSession()) {
            Log.d("VkDemoApp", "wakeUpSession");
            startLoading();
        } else {
            Log.d("VkDemoApp", "Login");
        }

    }

    public boolean postToWall() {
        boolean errorFlag = true;

        //String[] params =  //_vkSess.getAccessToken();

        //String accessToken = params[0];
        //String ownerId = params[2];

        //set request uri params
        VK_POST_TO_WALL_URL += "owner_id="+ tokenVk.userId+"&message="+ personImageURL+"&access_token="+tokenVk.accessToken;
        Log.d("Fuck",""+tokenVk.userId+" "+personImageURL+ " "+ tokenVk.accessToken);
        //send request to vkontakte api
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(VK_POST_TO_WALL_URL);
        Log.d("Fuck","request "+new HttpGet(VK_POST_TO_WALL_URL));
        try {
            Log.d("Fuck","request "+new HttpGet("owner_id="+ tokenVk.userId+"&message="+ personImageURL+"&access_token="+tokenVk.accessToken));
            HttpResponse response = client.execute(new HttpGet("owner_id="+ tokenVk.userId+"&message="+ personImageURL+"&access_token="+tokenVk.accessToken));

            HttpEntity entity = response.getEntity();

            String responseText = EntityUtils.toString(entity);
            Log.d("Fuck","response text="+responseText);
            //parse response for error code or not
            errorFlag = parseResponse(responseText);

            Log.d("Fuck","response text="+responseText);
        }
        catch(ClientProtocolException cexc){
            Log.d("Fuck","1");
            cexc.printStackTrace();

        }
        catch(IOException ioex){
            Log.d("Fuck","2");
            ioex.printStackTrace();

        }

        return errorFlag;
    }
    public boolean parseResponse(String jsonStr){
        boolean errorFlag = true;
        Log.d("Fuck","parse1");
        JSONObject jsonObj = null;
        try {
            Log.d("Fuck","parse2");
            jsonObj = new JSONObject(jsonStr);
            JSONObject errorObj = null;

            if( jsonObj.has("error") ) {
                Log.d("Fuck","parseError");
                errorObj = jsonObj.getJSONObject("error");
                int errCode = errorObj.getInt("error_code");
                if( errCode == 14){
                    errorFlag = false;
                }
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
            //Log.d(Constants.DEBUG_TAG,"exception when creating json object");
        }

        return errorFlag;
    }
    private final VKSdkListener sdkListener = new VKSdkListener() {
        //тут вроде как формируется токен для вк
        @Override
        public void onAcceptUserToken(VKAccessToken token) {
            tokenVk=token;
            Log.d("VkDemoApp", "onAcceptUserTokenVK " + token);
            startLoading();

        }

        @Override
        public void onReceiveNewToken(VKAccessToken newToken) {
            Log.d("VkDemoApp", "onReceiveNewTokenVK " + newToken.accessToken);
            Log.d("VkDemoApp", "onReceiveNewTokenVK " + VKSdk.isLoggedIn());
            tokenVk=newToken;
            startLoading();
        }

        @Override
        public void onRenewAccessToken(VKAccessToken token) {
            tokenVk=token;
            Log.d("VkDemoApp", "onRenewAccessTokenVK " + token);
            startLoading();
        }

        @Override
        public void onCaptchaError(VKError captchaError) {
            Log.d("VkDemoApp", "onCaptchaErrorVK " + captchaError);
        }

        @Override
        public void onTokenExpired(VKAccessToken expiredToken) {
            Log.d("VkDemoApp", "onTokenExpiredVK " + expiredToken);
        }

        @Override
        public void onAccessDenied(VKError authorizationError) {
            Log.d("VkDemoApp", "onAccessDeniedVK " + authorizationError);
        }

    };




    @Override
    protected void onResume() {
        Log.d(TAG, "Начался onResume");
        super.onResume();
        VKUIHelper.onResume(this);
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "Начался onStart");
        super.onStart();
        googleApiClient.connect();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "Начался onStop");
        super.onStop();
        if (googleApiClient.isConnected()) {
            googleApiClient.disconnect();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            Log.d(TAG, "Вошли в активити результ");
            if (resultCode!= RESULT_OK) {
                signInIsClicked = false;
            }
            intentInProgress = false;
            if (!googleApiClient.isConnecting()) {
                Log.d(TAG, "ApiClient is not Connecting");
                googleApiClient.connect();
            }
        }



        VKUIHelper.onActivityResult(this, requestCode, resultCode, data);//vk

        if (requestCode == 123 && resultCode == RESULT_OK) {// google
            final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            AsyncTask<Void, Void, String> getToken = new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    try {
                        tokenGoogle = GoogleAuthUtil.getToken(MainActivity.this, accountName,SCOPES);
                        Log.d(TAG, "Account ID: " +
                                GoogleAuthUtil.getAccountId(MainActivity.this, accountName));
                        Log.d("VkDemoApp", "tokenGoogle try" + tokenGoogle);
                        return tokenGoogle;

                    } catch (UserRecoverableAuthException userAuthEx) {
                        startActivityForResult(userAuthEx.getIntent(), 123);
                    }  catch (IOException ioEx) {
                        Log.d("VkDemoApp", "IOException");
                    }  catch (GoogleAuthException fatalAuthEx)  {
                        Log.d("VkDemoApp", "Fatal Authorization Exception" + fatalAuthEx.getLocalizedMessage());
                    }
                    Log.d("VkDemoApp", "Гугловский токен: " + tokenGoogle);
                    return tokenGoogle;
                }

                @Override
                protected void onPostExecute(String token) {
                    Log.d(TAG, "onPostExecute йоу, token: " + token);
                    //reg(tokenGoogle);
                    //передаем токен
                }


            };
            getToken.execute(null, null, null);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        VKUIHelper.onDestroy(this);
        if (currentRequest != null) {
            currentRequest.cancel();
        }
    }

    private void startLoading() {
        if (currentRequest != null) {
            currentRequest.cancel();
        }
        currentRequest = VKApi.friends().get(VKParameters.from(VKApiConst.FIELDS, "id,first_name,last_name,bdate"));

        //запросы вк
    }

    @Override
    public void onConnected(Bundle bundle) {
        signInIsClicked = false;
        Log.d(TAG, "Подключение произошло");
        getPhotos();
    }

    @Override
    public void onConnectionSuspended(int i) {
        googleApiClient.connect();
        Log.d(TAG, "Подключение запрещено");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Подключение зафейлилось");
        if (!connectionResult.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(),
                    this, 0).show();
            return;
        }
        if (!intentInProgress) {
            mConnectionResult = connectionResult;
            if (signInIsClicked) {
                resolveSignInError();
            }
        }
    }

    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                intentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (IntentSender.SendIntentException e) {
                intentInProgress = false;
                googleApiClient.connect();
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.signInButton:
                Log.d(TAG, "Нажата кнопка входа в Г+");
                Toast.makeText(getApplicationContext(),
                        "You pressed this, yeah!", Toast.LENGTH_SHORT).show();
                if (!googleApiClient.isConnecting()) {
                    signInIsClicked = true;
                    resolveSignInError();
                }
                break;
            default:
                Toast.makeText(getApplicationContext(),
                        "smth gonna wrong", Toast.LENGTH_LONG).show();
                break;
        }

    }

    private void getPhotos() {
        if (Plus.PeopleApi.getCurrentPerson(googleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi.getCurrentPerson(googleApiClient);
            String personName = currentPerson.getDisplayName();
            personImageURL = currentPerson.getImage().getUrl();
            Log.d(TAG, "name: " + personName);
            Log.d(TAG, "URL: " + personImageURL + " Cover ");
            Log.d(TAG, "Bragging Rights " + currentPerson.getBraggingRights()); //узнаем
            Log.d(TAG, "URLы: " + currentPerson.getUrl());
            personImageURL = personImageURL.substring(0,
                    personImageURL.length() - 2)
                    + 800;  //здесь мы меняем размер на нормаьный, по умолчанию 50рх, тут 800рх
            ImageView imageView = (ImageView)findViewById(R.id.imageView2);
            new LoadProfileImage(imageView).execute(personImageURL);


        }
    }
    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public LoadProfileImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
}